package com.cskaoyan.gateway.controller.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayChannelEnum;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.pay.dto.wechat.WechatPaymentResopnse;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

@RestController
public class PayController {
    private String imgPath = "http://localhost:8080/image/";

    @Reference(check = false,timeout = 3000)
    PayCoreService payCoreService;

    @PostMapping("cashier/pay")
    public ResponseData pay(@RequestBody Map<String,String> map, HttpServletRequest request){
        String userInfo = (String)request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        String payType = map.get("payType");

        PaymentRequest paymentRequest = new PaymentRequest();
        paymentRequest.setUserId(Long.parseLong(object.get("uid").toString()));
        paymentRequest.setTradeNo(map.get("orderId"));
        paymentRequest.setOrderFee(new BigDecimal(map.get("money")));
        paymentRequest.setTotalFee(new BigDecimal(map.get("money")));
        paymentRequest.setPayChannel(payType);
        paymentRequest.setSubject(map.get("info"));

        if(PayChannelEnum.ALI_PAY.getCode().equals(payType)) {
            AlipaymentResponse response = payCoreService.aliPay(paymentRequest);
            if(PayReturnCodeEnum.SUCCESS.getCode().equals(response.getCode())){
                return new ResponseUtil<>().setData(imgPath+response.getQrCode());
            }
        }else if(PayChannelEnum.WECHAT_PAY.getCode().equals(payType)){
            WechatPaymentResopnse resopnse = payCoreService.wxPay(paymentRequest);
            if(PayReturnCodeEnum.SUCCESS.getCode().equals(resopnse.getCode())){
                return new ResponseUtil<>().setData(imgPath+resopnse.getCodeUrl());
            }
        }
        return new ResponseUtil<>().setErrorMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
    }

    @GetMapping("cashier/queryStatus")
    public ResponseData queryStatus(String orderId){
        AlipayQueryRetResponse response = payCoreService.queryAlipayRet(orderId);
        if(!PayReturnCodeEnum.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(response.getMsg());
    }
}
